#import "MainViewController.h"

#define SUBMISSION_URL_FORMAT @"http://iphone.testiz.com/Add.php"



@implementation MainViewController

@synthesize flipDelegate, updateTextView, spinner;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		isCurrentlyUpdating = NO;
		firstUpdate = YES;
	}
	return self;
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[updateTextView release];
	[spinner release];
    [receivedData release];
	[super dealloc];
}

#pragma mark ---- control callbacks ----



// Tells the root view, via a delegate, to flip over to the FlipSideView
- (IBAction)infoButtonPressed:(id)sender {
	[self.flipDelegate toggleView:self];
}


- (void)displayNetworkError{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Error"
							message:@"There was an error connecting to the server."
							delegate:nil
							cancelButtonTitle:@"Ok"
						  otherButtonTitles:nil];
	[alert show];
	[alert release];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

// Appends some text to the main text view
// If this is the first update, it will replace the existing text
-(void)addTextToLog:(NSString *)text {
	if (firstUpdate) {
		updateTextView.text = text;
		firstUpdate = NO;
	} else {
		updateTextView.text = [NSString stringWithFormat:@"%@-----\n\n%@", updateTextView.text, text];
		[updateTextView scrollRangeToVisible:NSMakeRange([updateTextView.text length], 0)]; // scroll to the bottom on updates
	}
    
    
    NSString *post =  [ NSString stringWithFormat: @"%@", text ];
	NSLog(post);
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:@"http://iphone.testiz.com/add.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
	//NSString *comp = request;
	//NSLog(comp);
    if (conn)
    {
        receivedData = [[NSMutableData data] retain];
    }
    else
    {
        // inform the user that the download could not be made
		[self displayNetworkError];
    }
  
	[spinner stopAnimating]; 
    
/*	if (! isCurrentlyUpdating){
		[self startLocationService];
	}
*/	
	//if (isCurrentlyUpdating) {
//		[[MyCLController sharedInstance].locationManager stopUpdatingLocation];
//		isCurrentlyUpdating = NO;
//		[startStopButton setTitle:NSLocalizedString(@"StartButton", @"Start")];
//		[spinner stopAnimating];
//	} 
	
    
}



// Called when the view is loading for the first time only
// If you want to do something every time the view appears, use viewWillAppear or viewDidAppear


- (void)startLocationService {
    // Check to see if the user has disabled location services all together
    // In that case, we just print a message and disable the "Start" button
    if ( ! [MyCLController sharedInstance].locationManager.locationServicesEnabled ) {
        [self addTextToLog:NSLocalizedString(@"NoLocationServices", @"User disabled location services")];
    } else {
        [[MyCLController sharedInstance].locationManager startUpdatingLocation];
        isCurrentlyUpdating = YES;
        [spinner startAnimating];        
		NSLog(@"Updating");
    }
}


- (void)viewDidLoad {
	[MyCLController sharedInstance].delegate = self;
  //  [self startLocationService];
	
    NSTimer *currentTimer = [NSTimer scheduledTimerWithTimeInterval:300.0 target:self selector:@selector(startLocationService) userInfo:nil repeats:YES];
	
	[currentTimer fire];
	
	
	UIAlertView *alertTest = [[UIAlertView alloc]
							  initWithTitle:@"This is a Test"
							  message:@"This is the message contained with a UIAlertView"
							  delegate:self
							  cancelButtonTitle:@"Button #1"
							  otherButtonTitles:nil];
	
	[alertTest addButtonWithTitle:@"Button #2"];
	[alertTest show];
	[alertTest autorelease];
}


#pragma mark ---- delegate methods for the MyCLController class ----

-(void)newLocationUpdate:(NSString *)text {
	[self addTextToLog:text];
}

-(void)newError:(NSString *)text {
	[self addTextToLog:text];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
    NSLog(aStr);
    
    // release the connection, and the data object
    [receivedData release];
}

@end
